package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.BidsDAO;
import dao.InventoryDAO;
import dao.ProductsDAO;
import modal.ProductModal;
import modal.UserModal;

/**
 * Servlet implementation class AcceptBidController
 */
@WebServlet("/AcceptBidController")
public class AcceptBidController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AcceptBidController() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			doProcess(request,response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			doProcess(request,response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		UserModal user = (UserModal) session.getAttribute("user");
		BidsDAO bdao = new BidsDAO();
		ProductsDAO pdao =new ProductsDAO();
		ProductModal prod = (ProductModal) session.getAttribute("prod");
		
		if(user==null){
		response.sendRedirect("login.jsp");
		}
		if(prod.getOwnerId()==user.getUserId())
		{
			bdao.AddBid(prod.getProductId(), user.getUserId(), bdao.getHighestPricebyProductId(prod.getProductId()), 1);
		}else{
			bdao.AddBid(prod.getProductId(), user.getUserId(), bdao.getLowestOfferbyProductId(prod.getProductId()), 0);
			InventoryDAO iDao=new InventoryDAO();
			iDao.addProduct(prod.getProductId(), user.getUserId());
			iDao.disconnnect();
		}
		pdao.setStatusSold(prod.getProductId());
		request.getRequestDispatcher("/HomeController").forward(request, response);
	}

}
